#!/bin/bash
# Proof of concept direct connect to container
# rather than use attack container
#
# Author: Jon Kent

# poc-ssh [scenario name]
# e.g
# ./poc-ssh lazy_AWS

#set -euxo pipefail # debug
set -euo pipefail

scenarioName=${1:-1}

if [[ "${scenarioName}" == 1 ]] || [[ "${scenarioName}" =~ -*h[a-z]* ]]; then
	echo "Requires scenario name, e.g."
	echo "${0} lazy_AWS"
	exit 1
fi

dirName="$( cd "$( dirname "${BASH_SOURCE[0]}")" && pwd )"
belowDir=$(echo ${dirName} | sed -e 's/simulation-scripts//g')
scenarioDir="${dirName}/scenario/$1"
configFile=${scenarioDir}/MANIFEST.yaml
challenge="${scenarioDir}/challenge.txt"
tmpDir="/home/launch/.kubesim"

[ ! -d "${scenarioDir}" ] && { echo "Scenario directory not found, check name"; exit 1; }
[ ! -f "${configFile}" ] && { echo "Missing Manifest file, cannot continue"; exit 1; }
[ ! -f ~/.ssh/cp_simulator_config ] && { echo "Missing ssh config file, cannot continue"; exit 1; }

attackType=$(grep attack ${configFile} |awk -F: '{print$2}' | sed 's/ //g')
instanceType=$(grep instance ${configFile} |awk -F: '{print$2}' | sed 's/ //g')
containerName=$(grep container-name ${configFile} |awk -F: '{print$2}' | sed 's/ //g')

if [ "${attackType}" = "container" ]; then
	nodeIp=$(grep -h ${containerName} ${tmpDir}/docker-${instanceType}-* | grep -v pause | awk '{print$1}')
	dockerContainer=$(grep -h ${containerName} ${tmpDir}/docker-${instanceType}-* | grep -v pause | awk '{print$2}')

	[ -f "$challenge" ] && cat "$challenge"

	echo "Connecting to ${containerName} via host ${nodeIp}"

	ssh -F ~/.ssh/cp_simulator_config  -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" root@${nodeIp} docker exec -it ${dockerContainer} bash
else
	echo "Connecting to attack container"
	pushd "${belowDir}" > /dev/null
	simulator ssh attack
	popd > /dev/null
fi

